package com.example.demo02.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo02.entity.OrderDetails;
import com.example.demo02.entity.Product;
import com.example.demo02.mapper.OrderDetailsMapper;
import com.example.demo02.mapper.OrdersMapper;
import com.example.demo02.entity.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * (Orders)表服务实现类
 *
 * @author makejava
 * @since 2024-09-01 20:15:25
 */
@Service("orderService")
public class OrdersService extends ServiceImpl<OrdersMapper, Orders> {
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private ProductService productService; // 假设你有一个服务来处理产品相关逻辑
    @Autowired
    private OrdersMapper ordersMapper;

    @Transactional
    public Integer createOrder(Orders orders) {
        // 首先保存订单信息
        ordersMapper.insert(orders);
        // 获取数据库自动生成的订单 ID
        Integer orderId = orders.getOrderId();

        if (orderId == null) {
            throw new RuntimeException("订单 ID 生成失败");
        }
        // 遍历订单详情列表
        for (OrderDetails orderDetail : orders.getOrderDetails()) {
            // 检查库存
            Product product = productService.getById(orderDetail.getProductId());
            if (product.getStockQuantity() < orderDetail.getQuantity()) {
                throw new RuntimeException("库存不足");
            }
            // 减少库存
            productService.reduceStock(orderDetail.getProductId(), orderDetail.getQuantity());
            // 设置订单详情中的订单 ID
            orderDetail.setOrderId(orderId);
            // 保存订单详情
            orderDetailsMapper.insert(orderDetail);
        }
        return orderId; // 返回新创建的订单 ID
    }
}